// tools/audit-gm/alarm.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <syslog.h>
#include <errno.h>
#include <locale.h>

#include <libintl.h>
#ifndef _
#  define _(s) gettext(s)
#endif

/* i18n 绑定（主程序已 setlocale，这里只绑定域与编码） */
#ifndef GETTEXT_PACKAGE
#define GETTEXT_PACKAGE "audit-gm"
#endif
#ifndef LOCALEDIR
#define LOCALEDIR "/usr/local/share/locale"
#endif

static void alarm_i18n_bind(void)
{
    static int bound = 0;
    if (bound) return;
    bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
    bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
    textdomain(GETTEXT_PACKAGE);
    bound = 1;
}

static void ensure_dir(const char *dir) {
    struct stat st;
    if (stat(dir, &st) == -1) {
        mkdir(dir, 0755);
    }
}

void trigger_alarm(const char *message) {
    if (!message) return;

    alarm_i18n_bind();
    const char *tag = _("[ALARM]");

    // 1) stderr
    fprintf(stderr, "%s %s\n", _("[ALARM]"), message);

    // 2) 本地日志文件
    ensure_dir("/var/log/audit-gm");
    FILE *f = fopen("/var/log/audit-gm/alarm.log", "a");
    if (f) {
        time_t t = time(NULL);
        struct tm tm; localtime_r(&t, &tm);
        char ts[64];
        strftime(ts, sizeof(ts), "%F %T", &tm);
        /* 文件里也带上可译前缀，保持一致 */
        fprintf(f, "%s %s %s\n", ts, tag, message);
        fclose(f);
    } else {
        fprintf(stderr, "%s %s: %s\n", _("[ALARM]"), _("open failed"), strerror(errno));
    }

    // 3) syslog
    openlog("audit-alarm", LOG_PID|LOG_CONS, LOG_AUTH);
    /* syslog 里同样带上可译前缀 */
    syslog(LOG_ALERT, "%s %s", tag, message);
    closelog();
}
